<template>

  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <!-- 主表单区域 -->
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
          <a-col :span="6" >
            <a-form-model-item label="单据编号"  :labelCol="labelCol" :wrapperCol="wrapperCol" prop="code">
              <a-input v-model="model.code" disabled placeholder="请输入单据编号" ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="6" >
            <a-form-model-item label="流程类型" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="desFlowType">
              <j-dict-select-tag  disabled type="list" v-model="model.desFlowType" dictCode="constract_des_flow_type" placeholder="请选择流程类型" />
            </a-form-model-item>
          </a-col>
          <a-col :span="6" >
            <a-form-model-item label="客户" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="customerId" >
              <tsl-erp-customer v-model="model.customerId" @handlerok='changeCustomer'>

              </tsl-erp-customer>
<!--              <j-dict-select-tag type="list"  dictCode="erp_customer,name,id" placeholder="请选择客户" />-->
            </a-form-model-item>
          </a-col>
          <a-col :span="6" >
            <a-form-model-item label="业务员"  :labelCol="labelCol" :wrapperCol="wrapperCol" prop="salesman">
              <a-input v-model="model.salesman"  placeholder="请输入业务员" ></a-input>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-tabs   v-bind="$attrs" :disabled="false"   :default-active-key="tabkeys[0]"  @change="handleChangeTabs">
          <a-tab-pane  tab="合同评审说明信息"  :key="tabkeys[0]" :forceRender="true">

        <a-card >
          <template #title>
            <div class="custom-card-title">一、配方要求</div>
          </template>
        <a-row justify="start">
          <a-col :span="24" >
            <a-form-model-item   prop="formulaReq" >
              <a-textarea v-model="model.formulaReq" :rows="10" allow-clear showCount  placeholder="请输入配方要求" ></a-textarea>
            </a-form-model-item>
          </a-col>
        </a-row>
        </a-card>
        <a-card >
          <template #title>
            <div class="custom-card-title">二、包装要求</div>
          </template>
          <a-row justify="start">
          <a-col :span="36" >
            <a-form-model-item   prop="packReq">
              <a-textarea v-model="model.packReq" :rows="10" allow-clear showCount  placeholder="请输入包装要求" ></a-textarea>
            </a-form-model-item>
          </a-col>
          </a-row>
        </a-card>
        <a-card >
          <template #title>
            <div class="custom-card-title">三、价格条款</div>
          </template>
        <a-row>
          <a-col :span="6" >
            <a-form-model-item label="重量" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="weight">
              <a-input-number v-model="model.weight" placeholder="请输入重量" style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="6" >
            <a-form-model-item label="重量单位" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="weightUnit">
              <j-dict-select-tag type="list" v-model="model.weightUnit" dictCode="zl_unit" placeholder="请选择重量单位" />
            </a-form-model-item>
          </a-col>
          <a-col :span="6" >
            <a-form-model-item label="柜数" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="cabinetCount">
              <a-input v-model="model.cabinetCount" placeholder="请输入柜数" ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="6" >
            <a-form-model-item label="柜数单位" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="extra">
              <a-input v-model="model.extra" placeholder="请输入柜数单位" ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="6" >
            <a-form-model-item label="成交方式" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="transactionMethod">
              <a-input v-model="model.transactionMethod" placeholder="请输入成交方式" ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="6" >
            <a-form-model-item label="发货港" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="shipPort">
              <a-input v-model="model.shipPort" placeholder="请输入发货港" ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="6" >
            <a-form-model-item label="目的港" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="destPort">
              <a-input v-model="model.destPort" placeholder="请输入目的港" ></a-input>
            </a-form-model-item>
          </a-col>
        </a-row>
        </a-card>
        <a-card >
          <template #title>
            <div class="custom-card-title">四、付款方式</div>
          </template>
          <a-row>
          <a-col :span="6" >
            <a-form-model-item label="财务备录" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="financeRemark">
              <a-input v-model="model.financeRemark" placeholder="请输入财务备录" ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="6" >
            <a-form-model-item label="付款方式"  :labelCol="labelCol" :wrapperCol="wrapperCol" prop="payMethod">
              <a-input v-model="model.payMethod" placeholder="请输入付款方式" ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="6" >
            <a-form-model-item label="到货后付全款天数" label-width='100px'   :labelCol="labelCol" :wrapperCol="wrapperCol" prop="daysArrival">
              <a-input-number v-model="model.daysArrival" placeholder="请输入到货后付全款天数" style="width: 100%" />
            </a-form-model-item>
          </a-col>
          </a-row>
        </a-card>
        <a-card  v-if='model.desFlowType==1'>
          <template #title>
            <div class="custom-card-title">五、交货期</div>
          </template>
        <a-row>
          <a-col :span="6" >
            <a-form-model-item label="交货期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="deliveryTime">
              <a-input v-model="model.deliveryTime" placeholder="请输入交货期" ></a-input>
            </a-form-model-item>
          </a-col>
        </a-row>
        </a-card>
        <a-card v-if='model.desFlowType==1'>
          <template #title>
            <div class="custom-card-title">六、溢短装</div>
          </template>
          <a-row>
          <a-col :span="6" >
            <a-form-model-item label="溢短装" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="overflowShort">
              <a-input v-model="model.overflowShort" placeholder="请输入溢短装" ></a-input>
            </a-form-model-item>
          </a-col>
          </a-row>
        </a-card>
        <a-card v-if='model.desFlowType==1'>
          <template #title>
            <div class="custom-card-title">七、客户类型</div>
          </template>
          <a-row>
          <a-col :span="6" >
            <a-form-model-item label="客户类型" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="customer">
              <a-input v-model="model.customer" placeholder="请输入客户类型" ></a-input>
            </a-form-model-item>
          </a-col>
          </a-row>
        </a-card>
            <a-card>
              <template #title>
                <div class="custom-card-title">八、附件列表</div>
              </template>
              <j-vxe-table
                keep-source
                :ref="refKeys[0]"
                :loading="bussContractReviewDesFilesTable.loading"
                :columns="bussContractReviewDesFilesTable.columns"
                :dataSource="bussContractReviewDesFilesTable.dataSource"
                :maxHeight="300"
                :disabled="formDisabled"
                :rowNumber="true"
                :rowSelection="true"
                :toolbar="true"
              >
                <template v-slot:action="props">
                  <a @click="handlePreviewFile(props)">预览</a>
                </template>
              </j-vxe-table>
            </a-card>
          </a-tab-pane>
          <a-tab-pane  tab="状态履历修改" :key="tabkeys[1]" :forceRender="true">
            <tsl-history  dataTable="buss_contract_review_des"  :dataId="model.id"></tsl-history>
          </a-tab-pane>
        </a-tabs>
      </a-form-model>
    </j-form-container>
    <a-card>
      <a-row>
        <a-col :span="6" >
          <a-form-model-item label="制单人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="createBy">
            <a-input disabled v-model="model.createBy" placeholder="请输入制单人" ></a-input>
          </a-form-model-item>
        </a-col>
        <a-col :span="6" >
          <a-form-item label="制单部门" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="sysOrgCode">
            <j-select-depart disabled v-model="model.departIds" :multi="true"/>
          </a-form-item>
        </a-col>
        <a-col :span="6" >
          <a-form-model-item label="制单日期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="createTime">
            <a-input disabled v-model="model.createTime" placeholder="请输入制单日期" ></a-input>
          </a-form-model-item>



        </a-col>
      </a-row>
    </a-card>
  </a-spin>
</template>

<script>

import { getAction, getFileAccessHttpUrl, putAction } from '@/api/manage'
import store from '@/store'
//获取登录用户的信息
import { user } from '@/store/modules/user'
import { JVxeTableModelMixin } from '@/mixins/JVxeTableModelMixin.js'
import { JVXETypes } from '@/components/jeecg/JVxeTable'
import { getRefPromise,VALIDATE_FAILED} from '@/components/jeecg/JVxeTable/utils/vxeUtils.js'
import { validateDuplicateValue } from '@/utils/util'
import JFormContainer from '@/components/jeecg/JFormContainer'
import { Base64 } from 'js-base64';
import TslErpCustomer from '@comp/tsl/TslErpCustomer.vue'
import TslHistory from '@comp/tsl/TslHistory.vue'
export default {
  name: 'BussContractReviewDesForm',
  mixins: [JVxeTableModelMixin],
  components: {
    JFormContainer,TslErpCustomer,TslHistory
  },
  data() {
    return {
      tabkeys: ['info','uphistorys'],
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
        style: 'width: 32%;',
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      model:{
        desFlowType:1
      },
      // 新增时子表默认添加几行空数据
      addDefaultRowNum: 1,
      validatorRules: {
        code: [
          { required: true, message: '请输入单据编号!'},
        ],
        desFlowType: [
          { required: true, message: '请选择流程!'},
        ],
      },
      refKeys: ['bussContractReviewDesFiles','history' ],
      tableKeys:['bussContractReviewDesFiles', ],
      activeKey: 'bussContractReviewDesFiles',
      // 合同评审说明关联文件
      bussContractReviewDesFilesTable: {
        loading: false,
        dataSource: [],
        columns: [
          {
            title: '附件',
            key: 'filePath',
            type: JVXETypes.file,
            token:true,
            responseName:"message",
            width:"200px",
            placeholder: '请选择文件',
            defaultValue:'',
          },
          {
            title: '附件说明',
            key: 'fileDesc',
            type: JVXETypes.input,
            width:"200px",
            placeholder: '请输入${title}',
            defaultValue:'',
          },   {
            title: '操作',
            key: 'action',
            type: JVXETypes.slot,
            fixed: 'right',
            minWidth: '100px',
            align: 'center',
            slotName: 'action',
          }
        ]
      },
      url: {
        add: "/business/bussContractReviewDes/add",
        edit: "/business/bussContractReviewDes/edit",
        queryById: "/business/bussContractReviewDes/queryById",
        bussContractReviewDesFiles: {
          list: '/business/bussContractReviewDes/queryBussContractReviewDesFilesByMainId'
        },
      }
    }
  },
  props: {
    //表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false
    },
    customFormData:{
      type:Object,
      default:()=>{return {}},
      required:false
    },
  },
  computed: {
    formDisabled(){
      return this.disabled
    },
  },
  created () {
    console.log('model='+this.model)
    if(this.customFormData != null) {

      console.log("this.customFormData=",this.customFormData);
      console.log("dis",this.formDisabled)
      this.model = this.customFormData;
      this.editAfter();  //现在子表内容需要
      let user= store.getters.userInfo
      if (!this.model.createBy){
        console.log(user)
        this.model.createBy=user.username
        this.model.departIds=user.departIds
        const now = new Date();
        this.model.createTime=this.formatDate(now)

        // this.model.salesman=user.username

      }
    }
  },
  methods: {
    changeCustomer(value){
      getAction("/business/bussContractReviewDes/querySalesman",{id:value}).then(res=>{
        console.log(res)
        if (res.success){
           this.model.salesman=res.result.salesman
         let type =  res.result.type
          if (type&&type.name==='国内/OEM'){
            this.model.desFlowType=2
          }
          if (type&&type.name==='国贸'){
            this.model.desFlowType=1
          }
        } else {

        }
      })
    },
    getImgView(text){
      if(text && text.indexOf(",")>0){
        text = text.substring(0,text.indexOf(","))
      }
      return getFileAccessHttpUrl(text)
    },
     formatDate(date) {
       const year = date.getFullYear();
       const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始，使用padStart方法补齐两位数
       const day = String(date.getDate()).padStart(2, '0'); // 日期补齐两位数
       const hours = String(date.getHours()).padStart(2, '0'); // 小时补齐两位数
       const minutes = String(date.getMinutes()).padStart(2, '0'); // 分钟补齐两位数
       const seconds = String(date.getSeconds()).padStart(2, '0'); // 秒补齐两位数

       return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
},

    handlePreviewFile(row) {
      let filePath=row.row.filePath
      let reviewUrl = this.getImgView(filePath)
      let rowpath = reviewUrl.replace(/\\/g, '/');
      let base = window._CONFIG.onlinePreviewDomainURL + "/onlinePreview?url="
      let codename = Base64.encode(rowpath);
      let url = base + codename + '&watermarkTxt=' + encodeURIComponent(store.getters.userInfo.username)
      window.open(url, '_blank')
    },
    getSequenceNum() {
      let url = "/sys/fillRule/executeRuleByCode/htpssm";
      putAction(url, {}).then(res => {
        // 执行成功，获取返回的值，并赋到页面上
        if (res.success) {
          this.model.code = res.result;
        }
      })
    },
    addBefore(){
      this.bussContractReviewDesFilesTable.dataSource=[]
      this.getSequenceNum()
    },
    getAllTable() {
      let values = this.tableKeys.map(key => getRefPromise(this, key))
      return Promise.all(values)
    },
    /** 调用完edit()方法之后会自动调用此方法 */
    editAfter() {
      this.$nextTick(() => {
      })
      // 加载子表数据
      if (this.model.id) {
        let params = { id: this.model.id }
        this.requestSubTableData(this.url.bussContractReviewDesFiles.list, params, this.bussContractReviewDesFilesTable)
      }
    },
    //校验所有一对一子表表单
    validateSubForm(allValues){
      return new Promise((resolve,reject)=>{
        Promise.all([
        ]).then(() => {
          resolve(allValues)
        }).catch(e => {
          if (e.error === VALIDATE_FAILED) {
            // 如果有未通过表单验证的子表，就自动跳转到它所在的tab
            this.activeKey = e.index == null ? this.activeKey : this.refKeys[e.index]
          } else {
            console.error(e)
          }
        })
      })
    },
    /** 整理成formData */
    classifyIntoFormData(allValues) {
      let main = Object.assign(this.model, allValues.formValue)
      return {
        ...main, // 展开
        bussContractReviewDesFilesList: allValues.tablesValue[0].tableData,
      }
    },
    validateError(msg){
      this.$message.error(msg)
    },

  }
}
</script>

<style scoped>
.custom-card-title {
  font-size: 16px;
  font-weight: bold;
}
</style>